import { useState, useCallback } from 'react';

// 通用表格状态接口
export interface TableState<T = any> {
  data: T[];
  loading: boolean;
  total: number;
  current: number;
  pageSize: number;
  selectedRowKeys: React.Key[];
  filters: Record<string, any>;
  sorter: {
    field?: string;
    order?: 'ascend' | 'descend';
  };
}

// 表格状态初始值
const getInitialState = <T>(initialFilters: Record<string, any> = {}): TableState<T> => ({
  data: [],
  loading: false,
  total: 0,
  current: 1,
  pageSize: 20,
  selectedRowKeys: [],
  filters: initialFilters,
  sorter: {},
});

// 通用表格状态管理Hook
export const useTableState = <T = any>(initialFilters: Record<string, any> = {}) => {
  const [state, setState] = useState<TableState<T>>(getInitialState<T>(initialFilters));

  // 设置加载状态
  const setLoading = useCallback((loading: boolean) => {
    setState(prev => ({ ...prev, loading }));
  }, []);

  // 设置数据
  const setData = useCallback((data: T[], total?: number) => {
    setState(prev => ({ 
      ...prev, 
      data, 
      total: total !== undefined ? total : prev.total 
    }));
  }, []);

  // 设置分页
  const setPagination = useCallback((current: number, pageSize?: number) => {
    setState(prev => ({ 
      ...prev, 
      current, 
      pageSize: pageSize || prev.pageSize 
    }));
  }, []);

  // 设置筛选条件
  const setFilters = useCallback((filters: Record<string, any>) => {
    setState(prev => ({ 
      ...prev, 
      filters: { ...prev.filters, ...filters },
      current: 1 // 重置到第一页
    }));
  }, []);

  // 设置排序
  const setSorter = useCallback((field: string, order?: 'ascend' | 'descend') => {
    setState(prev => ({ 
      ...prev, 
      sorter: { field, order },
      current: 1 // 重置到第一页
    }));
  }, []);

  // 设置选中行
  const setSelectedRowKeys = useCallback((selectedRowKeys: React.Key[]) => {
    setState(prev => ({ ...prev, selectedRowKeys }));
  }, []);

  // 重置状态
  const reset = useCallback(() => {
    setState(getInitialState<T>(initialFilters));
  }, [initialFilters]);

  // 刷新数据（保持当前状态）
  const refresh = useCallback(() => {
    setState(prev => ({ ...prev, loading: true }));
  }, []);

  return {
    state,
    setState,
    setLoading,
    setData,
    setPagination,
    setFilters,
    setSorter,
    setSelectedRowKeys,
    reset,
    refresh,
  };
};

export default useTableState;
